package com.example.demo.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.example.demo.entity.Car;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;

@Controller
@RequestMapping("haha")
@SessionAttributes(value= {"xixi"},types= {String.class})
public class HahaController {

	@GetMapping("ye")
//	@ResponseBody
	public String haha() {
		return "haha";
	}
	
	@Resource
	private UserService userService;
	
	@PostMapping("xixi")
	@ResponseBody
	public Object xixi(@Valid User user) {
		User addUser = userService.addUser(user);
		return addUser;
		
	}
	
	@GetMapping("by_name")
	@ResponseBody
	public Object getByName(String name) {
		return userService.getByName(name);
	}
	

	@GetMapping("by_id")
	@ResponseBody
	public Object getById(Integer id) {
		return userService.getUser(id);
	}
	
	@GetMapping("del")
	@ResponseBody
	public Object del(Integer id) {
		 userService.remove(id);
		 return "删除成功";
	}
	
	
	@GetMapping("one")
	@ResponseBody
	public String one(@RequestParam("cc") String aa,
			@RequestParam(value="dd",required=true,defaultValue="12") int dd,
			@RequestHeader("User-Agent") String agent,
			@CookieValue("JSESSIONID") String jsessionId) {
		return "<h1>"+aa+dd+agent+"|"+jsessionId+"</h1>";
		
	}
	
	@GetMapping("two")
	public void two(HttpServletRequest req,PrintWriter resp) throws IOException {
		Cookie[] cookies = req.getCookies();
		for (Cookie cookie : cookies) {
			if(cookie.getName().equals("JSESSIONID")) {
				resp.println(cookie.getValue());
			}
		}
	}
	
	@GetMapping("three")
	public String three(Map<String,Object> map) {
		User user = new User();
		user.setName("张三丰");
		user.setAge(100);
		Car car = new Car();
		car.setBand("比亚迪");
		car.setPrice(35687.34);
		user.setCar(car);
		map.put("user", user);//加入到request作用域内
		map.put("xixi", 888);
		map.put("abc", "今天天气真好");
		map.put("dbc", new Date());
		
		return "hehe";
	}
}
